<template>
  <form-dialog ref="formDrawerRef" title="预审" top="2vh" width="98%" @submit="handleSubmit">
    <div class="dialog-body">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="160px">
        <el-row :gutter="0">
          <el-col v-for="item in configList" :key="item.value"
            :span="item.value == 'typeLevel' && form['carCategory'] != 1 ? 0 : item.span">
            <template v-if="item.types === 'input'">
              <el-form-item :label="item.label" :prop="item.value">
                <el-input v-model="form[item.value]" :placeholder="item.placeholder"></el-input>
              </el-form-item>
            </template>
            <template v-else-if="item.types === 'select'">
              <div v-if="item.value == 'typeLevel'">
                <el-form-item v-if="form['carCategory'] == 1" :label="item.label" :prop="item.value">
                  <el-select v-model="form[item.value]" :placeholder="item.placeholder">
                    <el-option v-for="option in item.options" :key="option.value" :label="option.label"
                      :value="option.value"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <el-form-item v-else :label="item.label" :prop="item.value">
                <el-select v-model="form[item.value]" :placeholder="item.placeholder">
                  <el-option v-for="option in item.options" :key="option.value" :label="option.label"
                    :value="option.value"></el-option>
                </el-select>
              </el-form-item>
            </template>
            <template v-else-if="item.types === 'time'">
              <el-form-item :label="item.label" :prop="item.value">
                <template v-if="item.value == 'nowValidityTime'">
                  <el-date-picker v-model="form[item.value]" :type="item.type" placeholder="请选择本次年审日期"
                    value-format="YYYY-MM-DD" :disabled-date="handleDisabledDate" style="width: 100%"></el-date-picker>
                </template>
                <template v-else>
                  <el-date-picker v-model="form[item.value]" :type="item.type" placeholder="请选择日期"
                    value-format="YYYY-MM-DD" style="width: 100%"></el-date-picker>
                </template>
              </el-form-item>
            </template>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="tableData" border :header-cell-style="{ color: '#fff', backgroundColor: '#409EFF' }">
        <el-table-column type="index" width="60" label="序号" header-align="center" align="center" />
        <el-table-column prop="materialName" label="审验材料名称" width="320" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="department" label="审批人" width="220" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="imgNum" label="需要拍照数目" width="120" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="saveImgNum" label="已拍照片数目" width="120" header-align="center"
          align="center"></el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="handleFileManage(row, '')">上传文件</el-button>
            <el-button type="primary" size="mini" @click="handleFileManage(row, 'disabled')">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <form-dialog ref="detailRef" :appendToBody="true" top="30vh" width="50%" @submit="handleSubmitImg">
        <template #header>
          <span class="font-bold">上传</span>
        </template>
        <div class="dialog-detail">
          <div class="filming" v-if="currentFileRow.imgNum == '不限制' || currentFileRow.imgNum > curImgList.length"
            @click="openFilming">
            <el-icon :size="30">
              <Camera />
            </el-icon>
          </div>
          <upload-img ref="uploadImgRef" :limit="currentFileRow.imgNum == '不限制' ? 999 : currentFileRow.imgNum"
            :autoUpload="false" :disabled="disabledUpload" :imgList="curImgList" @remove="handleRemove"
            @success="handleUpdateImg" :call-back="uploadCallBack"></upload-img>
        </div>
      </form-dialog>
    </div>
  </form-dialog>

  <el-dialog v-model="cameraDialogShow" title="拍摄" fullscreen style="height: 100vh;" @close="cameraDialogClose">
    <div style="width: 100%; height:100%;">
      <canvas v-show="camerImage" ref="camerCanvas" width="960" height="720"></canvas>
      <video v-show="!camerImage" ref="cameraDialogVideo" width="960" height="720" autoplay></video>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="offDialogShow">{{ camerImage ? '重拍' : '取消' }}</el-button>
        <el-button type="primary" @click="photograph">{{ camerImage ? '确定' : '拍摄' }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { useInitForm } from "@/hooks/useCommon";
import FormDialog from "@/components/FormDialog.vue";
import { ElMessage } from "element-plus";
// 导入图片上传组件
import UploadImg from "@/components/UploadImg.vue";
// 导入获取材料列表的api
import { getAnnualReviewRecordBySign, confirmAnnualReviewRecord } from "@/api/annualAudit";

// 当前日期后面的时间不可选
const handleDisabledDate = (time: any) => {
  return time.getTime() > Date.now();
};


const { formDrawerRef, formRef, form, rules, handleEdit } = useInitForm({
  form: {
    // 这里设置默认值
    xctAnnualVerificationMaterialsList: [],
    operatorPhone: "",
    validityTime: "",
    inspectionId: "",
    checkTime: "",
    nowValidityTime: "",
    nowEvaluationTime: "",
    levelValid: "",
    nextEvaluationTime: "",
    vehicleLevel: "",
    evaluationTime: "",
    typeLevel: "",
    isInstallVideo: "",
    gpsLoginTime: "",
    isOnlineYear: "",
    coverageType: "1",
    isValid: "",
    startCoverageTime: "",
    endCoverageTime: "",
    transportationDepartment: ""
  },
  rules: {
    operatorPhone: [
      { required: true, message: "请输入经办人电话", trigger: "blur" },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (!/^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/.test(value)) {
            callback(new Error("请输入正确的号码,座机用-"));
          } else {
            callback();
          }
        }
      }
    ],
    validityTime: [{ required: true, message: "请选择下次年审日期", trigger: "blur" }],
    inspectionId: [{ required: true, message: "请输入检测单号", trigger: "blur" }],
    checkTime: [{ required: true, message: "请选择检测日期", trigger: "blur" }],
    nowValidityTime: [{ required: true, message: "请选择本次年审日期", trigger: "blur" }],
    nowEvaluationTime: [{ required: true, message: "请选择等级评定日期", trigger: "blur" }],
    levelValid: [{ required: true, message: "请选择等级有效期", trigger: "blur" }],
    nextEvaluationTime: [{ required: true, message: "请选择下次等级评定日期", trigger: "blur" }],
    vehicleLevel: [{ required: true, message: "请选择车辆技术等级", trigger: "blur" }],
    evaluationTime: [{ required: true, message: "请选择客车评定日期", trigger: "blur" }],
    typeLevel: [{ required: true, message: "请选择客车类型等级", trigger: "blur" }],
    isInstallVideo: [{ required: true, message: "请选择是否安装视频监控设备", trigger: "blur" }],
    gpsLoginTime: [{ required: true, message: "请选择GPS最后上线时间", trigger: "blur" }],
    isOnlineYear: [{ required: true, message: "请选择最近一年是否上线", trigger: "blur" }],
    coverageType: [{ required: true, message: "请选择投保险种", trigger: "blur" }],
    isValid: [{ required: true, message: "请选择是否有效保单", trigger: "blur" }],
    startCoverageTime: [{ required: true, message: "请选择起保日期", trigger: "blur" }],
    endCoverageTime: [{ required: true, message: "请选择终保日期", trigger: "blur" }],
    transportationDepartment: [{ required: true, message: "请输入车籍地运输交通部门", trigger: "blur" }]
  }
});
const configList = ref([{
  types: "input",
  span: 6,
  label: "经办人电话",
  value: "operatorPhone",
  width: "100px",
  placeholder: "请输入经办人电话"
}, {
  types: "time",
  span: 6,
  label: "本次年审日期",
  value: "nowValidityTime",
  width: "100px",
  placeholder: "需与实际年审日期一致"
}, {
  types: "time",
  span: 6,
  label: "年审有效期至",
  value: "validityTime",
  width: "120px",
  placeholder: "请选择下次年审日期"
}, {
  types: "input",
  span: 6,
  label: "检测单号",
  value: "inspectionId",
  width: "100px",
  placeholder: "需与实际检测单号一致"
}, {
  types: "time",
  span: 6,
  label: "检测日期",
  value: "checkTime",
  width: "100px",
  placeholder: "需与实际检测日期一致"
}, {
  types: "time",
  span: 6,
  label: "等级评定日期",
  value: "nowEvaluationTime",
  width: "100px",
  type: "month",
  placeholder: "请选择等级评定日期"
}, {
  types: "select",
  span: 6,
  label: "等级有效期",
  value: "levelValid",
  width: "100px",
  placeholder: "请选择等级有效期",
  options: [{
    label: "6个月",
    value: "1"
  }, {
    label: "12个月",
    value: "2"
  }]
}, {
  types: "time",
  span: 6,
  label: "下次等级评定日期",
  value: "nextEvaluationTime",
  width: "140px",
  type: "month",
  placeholder: "请选择下次等级评定日期"
}, {
  types: "select",
  span: 6,
  label: "车辆技术等级",
  value: "vehicleLevel",
  width: "100px",
  placeholder: "请选择车辆技术等级",
  options: [{
    label: "未评定",
    value: "1"
  }, {
    label: "一级",
    value: "2"
  }, {
    label: "二级",
    value: "3"
  }]
}, {
  types: "time",
  span: 6,
  label: "客车评定日期",
  value: "evaluationTime",
  width: "140px",
  type: "month",
  placeholder: "请选择下次等级评定日期"
}, {
  types: "select",
  span: 6,
  label: "客车类型等级", //车辆类别显示为客运车辆时，显示客车类型等级
  value: "typeLevel",
  width: "100px",
  placeholder: "请选择客车类型等级",
  options: [{
    label: "特大型高三级",
    value: "1"
  }, {
    label: "特大型高二级",
    value: "2"
  }, {
    label: "特大型高一级",
    value: "3"
  }, {
    label: "特大型中级",
    value: "4"
  }, {
    label: "特大型普通级",
    value: "5"
  }, {
    label: "大型高三级",
    value: "6"
  }, {
    label: "大型高二级",
    value: "7"
  }, {
    label: "大型高一级",
    value: "8"
  }, {
    label: "大型中级",
    value: "9"
  }, {
    label: "大型普通级",
    value: "10"
  }, {
    label: "中型高二级",
    value: "11"
  }, {
    label: "中型高一级",
    value: "12"
  },
  {
    label: "中型中级",
    value: "13"
  }, {
    label: "中型普通级",
    value: "14"
  }, {
    label: "小型高二级",
    value: "15"
  }, {
    label: "小型高一级",
    value: "16"
  }, {
    label: "小型中级",
    value: "17"
  }, {
    label: "小型普通级",
    value: "18"
  }, {
    label: "乘用车高级",
    value: "19"
  }, {
    label: "乘用车中级",
    value: "20"
  }, {
    label: "其他",
    value: "21"
  }]
}, {
  types: "select",
  span: 6,
  label: "是否安装视频监控设备",
  value: "isInstallVideo",
  width: "100px",
  placeholder: "请选择是否安装视频监控设备",
  options: [{
    label: "是",
    value: 0
  }, {
    label: "否",
    value: 1
  }]
}, {
  types: "time",
  span: 6,
  label: "GPS最后上线时间",
  value: "gpsLoginTime",
  width: "140px",
  placeholder: "请选择GPS最后上线时间"
}, {
  types: "select",
  span: 6,
  label: "最近一年是否上线",
  value: "isOnlineYear",
  width: "100px",
  placeholder: "请选择最近一年是否上线",
  options: [{
    label: "是",
    value: 0
  }, {
    label: "否",
    value: 1
  }]
}, {
  types: "select",
  span: 6,
  label: "投保险种",
  value: "coverageType",
  width: "100px",
  placeholder: "请选择投保险种",
  options: [
    {
      label: "营业性",
      value: "1"
    },
    {
      label: "非营业性",
      value: "2"
    }
  ]
}, {
  types: "select",
  span: 6,
  label: "是否有效保单",
  value: "isValid",
  width: "100px",
  placeholder: "请选择是否有效保单",
  options: [{
    label: "否",
    value: 1
  }, {
    label: "是",
    value: 0
  }]
}, {
  types: "time",
  span: 6,
  label: "起保日期",
  value: "startCoverageTime",
  width: "140px",
  placeholder: "请选择起保日期"
}, {
  types: "time",
  span: 6,
  label: "终保日期",
  value: "endCoverageTime",
  width: "140px",
  placeholder: "请选择终保日期"
}, {
  types: "input",
  span: 6,
  label: "车籍地运输交通部门",
  value: "transportationDepartment",
  width: "160px",
  placeholder: "请输入车籍地运输交通部门"
}]);

// 监听 nowEvaluationTime 和 levelValid 的变化
const tableData: any = ref([])
watch(
  () => [form.nowEvaluationTime, form.levelValid],
  ([nowEvaluationTime, levelValid]) => {
    if (nowEvaluationTime && levelValid) {
      const date = new Date(nowEvaluationTime);
      const monthsToAdd = levelValid === "1" ? 6 : 12;
      date.setMonth(date.getMonth() + monthsToAdd);
      form.nextEvaluationTime = date.toISOString().split("T")[0];
    }
  }
);

watch(
  () => [form.acceptanceId],
  ([newVal]) => {
    getAnnualReviewRecordBySign(newVal).then((res) => {
      tableData.value = res;
    });
  }
);

const currentFileRow: any = ref({})
const disabledUpload: any = ref(false)
// 文件管理
const handleFileManage = (row: any, disabled: string) => {
  // curTitle.value = `上传图片 -${row.project}- 所需图片${row.limit}张`;
  disabledUpload.value = disabled == "disabled" ? true : false;
  currentFileRow.value = row;
  handleDetail(row);
};
// 上传图片-弹框
const detailRef = ref();
const handleDetail = (row: any) => {
  curImgList.value = currentFileRow.value.curImgList ? currentFileRow.value.curImgList : [];
  detailRef.value.open(row);
};
// 图片列表
const curImgList = ref<any[]>([]);
const handleUpdateImg = (list: any) => {
  ElMessage.success("上传成功");
  // curImgList.value = list;
  currentFileRow.value.curImgList = list;
  currentFileRow.value.saveImgNum = list.length;
  const arr = list.map((item: any) => ({
    id: currentFileRow.value.id,
    photo: item.url
  }));
  if (
    form.xctAnnualVerificationMaterialsList &&
    form.xctAnnualVerificationMaterialsList.length >= 0
  ) {
    form.xctAnnualVerificationMaterialsList = form.xctAnnualVerificationMaterialsList.filter((item: any) => item.id != currentFileRow.value.id)
    form.xctAnnualVerificationMaterialsList.push(...arr);
  } else {
    form.xctAnnualVerificationMaterialsList = [];
    form.xctAnnualVerificationMaterialsList.push(...arr);
  }
  detailRef.value.hideLoading();
  detailRef.value.close();
};
// 删除图片
const handleRemove = (list: any) => {
  curImgList.value = list;
};
const uploadImgRef = ref();
// 上传图片-确定
const handleSubmitImg = () => {
  detailRef.value.showLoading();
  uploadImgRef.value.handleManualUpload();
};

const emit = defineEmits(["refresh"]);

// 表单验证
const handleSubmit = () => {
  (formRef as any).value.validate((valid: any) => {
    if (valid) {
      // 验证成功
      // 除了验证表单的内容意外，还要验证图片是否上传足够的数量
      let imgValid: boolean = true;
      tableData.value.forEach((item: any) => {
        if (item.imgNum != "不限制") {
          const num = item.saveImgNum ? item.saveImgNum : 0;
          if (num < item.imgNum) {
            ElMessage.error(`${item.materialName} 图片数量不足`);
            imgValid = false;
            return;
          }
        }
      });
      if (!imgValid) {
        return;
      }
      // return;
      confirmAnnualReviewRecord(form).then((res) => {
        if (res) {
          ElMessage.success("提交成功");
          // emit("close");
          (formDrawerRef.value as any).close()
          emit("refresh")
        }
      });
    }
  });
};

const cameraDialogShow = ref(false)
const cameraDialogVideo: any = ref(null)
const camerCanvas: any = ref(null)
const camerImage: any = ref(void 0)
const camerstream: any = ref(void 0)
const options = ref(new Array())
const openFilming = () => {
  ElMessage('摄像头开启中...')
  globalThis.navigator.mediaDevices.enumerateDevices()
    .then(devices => options.value.push(...devices.filter(item => item.kind == 'videoinput')))
    .then(() => globalThis.navigator.mediaDevices.getUserMedia({ video: true }))
    .then(success => {
      cameraDialogShow.value = true
      nextTick(() => {
        if (cameraDialogVideo.value) {
          // 摄像头开启成功
          cameraDialogVideo.value.srcObject = success
          // 实时拍照效果
          cameraDialogVideo.value.play()
        }
      })
      camerstream.value = success
    }).catch(() => {
      ElMessage.error('摄像头开启失败，请检查摄像头是否可用并重新打开！')
    })
}
const photograph = () => {
  if (camerImage.value) {
    const name = Date.now() + '.jpeg'
    const url = globalThis.URL.createObjectURL(camerImage.value)
    const raw = new globalThis.File([camerImage.value], name)
    curImgList.value = [...curImgList.value, { name, url, raw }]
    cameraDialogShow.value = false
  } else {
    if (camerCanvas.value) {
      const ctx = camerCanvas.value.getContext('2d')
      ctx.drawImage(cameraDialogVideo.value, 0, 0, 960, 720)
      camerCanvas.value.toBlob((blobImage: any) => {
        camerImage.value = blobImage
      }, 'image/jpeg')
    }
  }
}
const offDialogShow = () => {
  if (camerImage.value) {
    camerImage.value = null
  } else {
    cameraDialogShow.value = false
  }
}
const uploadCallBack = (newVal: any) => {
  curImgList.value = newVal
}
const cameraDialogClose = () => {
  camerstream.value.getVideoTracks().forEach((track: { stop: () => void; }) => {
    track.stop()
  })

}

defineExpose({
  handleEdit
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 200px);
  overflow-y: auto;
  overflow-x: hidden;
}

.filming {
  width: 98px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #cdd0d6;
  border-radius: 6px;
  background-color: #fafafa;
}

.filming:hover {
  cursor: pointer;
  border: 1px dashed #409eff;
}
</style>
